// src/stores/user.js

import { defineStore } from 'pinia'
import { getUserInfo } from '@/api/users'

export const useUserStore = defineStore('user', {
  // 定义 store 的状态
  state: () => ({
    userInfo: null,
    token: localStorage.getItem('token') || null,
  }),

  // 定义 actions
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    // 设置 token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 获取用户信息
    async fetchUserInfo() {
      if (this.token) {
        try {
          console.log('开始请求用户信息')
          const response = await getUserInfo()
          console.log('用户信息响应', response)
          if (response.code === 0) {
            const { userName, role, createTime, lastLoginTime,userId } = response.data
            this.setUserInfo({ userName, role, createTime, lastLoginTime ,userId})
            console.log('用户信息设置成功', this.userInfo)
          } else {
            console.error('获取用户信息失败', response.message)
            this.clearUserInfo()
          }
        } catch (error) {
          console.error('获取用户信息出错', error)
          this.clearUserInfo()
        }
      } else {
        console.log('没有token，不获取用户信息')
      }
    },

    // 清除用户信息
    clearUserInfo() {
      this.userInfo = null
      this.token = null
      localStorage.removeItem('token')
    },

    // 登出
    logout() {
      this.clearUserInfo()
    },
  },

  // 定义 getters
  getters: {
    // 判断是否登录
    isLoggedIn: (state) => !!state.userInfo,
    // 获取用户名
    userName: (state) => state.userInfo?.userName || '',
    // 获取用户角色
    userRole: (state) => state.userInfo?.role || '',
  },
})